<template>
  <div>
    <v-viewer ref="view"></v-viewer>
    <el-form size="medium"
             label-position="right"
             label-width="200px">
      <div class="breach-area">
        <div class="title">
          <div class="point"></div>
          <span>基础信息</span>
        </div>
        <el-form-item label="区域"
                      required>
          <el-radio v-model="product.area"
                    label=1>全国</el-radio>
          <el-radio v-model="product.area"
                    label=2>&nbsp;</el-radio>
          <el-select v-model="product.cityIds"
                     multiple
                     filterable
                     collapse-tags
                     placeholder="试试搜索"
                     :disabled="product.area === '1'">
            <el-option-group v-for="group in cityList"
                             :key="group.id"
                             :value="group.id"
                             :label="group.cityname">
              <el-option v-for="item in group.children"
                         :key="item.id"
                         :label="item.cityname"
                         :value="item.id">
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="金融产品公司全称">
          <el-select v-model="product.supplierId"
                     filterable
                     placeholder="请选择金融产品公司"
                     @change="setDetail(product.supplierId)">
            <el-option v-for="item in companyList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
          <el-button plain
                     type="primary"
                     size="mini"
                     @click="() => { this.$router.push({ name: 'supplier' }) }">新增</el-button>
        </el-form-item>
        <el-form-item label="金融产品经理">
          <el-col :span="7">
            <el-form-item>
              <el-input v-model="product.manager"
                        size="medium"
                        disabled></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="手机号">
          <el-col :span="7">
            <el-form-item>
              <el-input v-model.number="product.managerPhone"
                        size="medium"
                        disabled></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="方案名称"
                      required>
          <el-col :span="7">
            <el-form-item>
              <el-input v-model="product.productName"
                        placeholder="方案名称"
                        size="medium"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="产品图片"
                      required>
          <pic-view :pic-url-list.sync="product.productPicUrlList"
                    upload-class="short-upload"
                    :pic-name-list.sync="product.productPicNameList"
                    :upload-data="{ picName: 'product/presentCar' }"
                    :max-size="1"
                    :upload-type="isInfo"
                    @showImg="showImg"></pic-view>
        </el-form-item>
        <el-form-item label="车型"
                      required
                      v-model="product.carModelId">
          <el-select v-model="product.brandId"
                     filterable
                     placeholder="请选择品牌"
                     :disabled="vListLength(product.brandList)"
                     @change="getCarSeries(product.brandId)">
            <el-option v-for="item in product.brandList"
                       :key="item.brandId"
                       :label="item.brandName"
                       :value="item.brandId">
            </el-option>
          </el-select>
          <el-select v-model="product.seriesId"
                     filterable
                     placeholder="请选择车系"
                     :disabled="vListLength(product.seriesList)"
                     @change="getCarModel(product.seriesId)">
            <el-option v-for="item in product.seriesList"
                       :key="item.seriesId"
                       :label="item.seriesName"
                       :value="item.seriesId">
            </el-option>
          </el-select>
          <el-select v-model="product.modelId"
                     filterable
                     placeholder="请选择车型"
                     :disabled="vListLength(product.modelList)"
                     @change="setCarModelAndColors()">
            <el-option v-for="item in product.modelList"
                       :key="item.modelId"
                       :label="item.modelName"
                       :value="item.modelId">
            </el-option>
          </el-select>
          <el-select v-model="product.color"
                     multiple
                     filterable
                     allow-create
                     default-first-option
                     collapse-tags
                     placeholder="请选择颜色">
            <el-option v-for="item in product.colorList"
                       :key="item"
                       :label="item"
                       :value="item">
            </el-option>
          </el-select>
          <el-button plain
                     type="primary"
                     size="mini"
                     @click="() => { this.carDialog = true }">新增车型</el-button>
        </el-form-item>
        <el-form-item label="市场指导价">
          <el-col :span="7">
            <el-form-item>
              <el-input v-model.number="product.carPrice"
                        size="medium"
                        readonly>
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="车辆类型"
                      required>
          <el-radio v-model="product.carType"
                    label="新车"
                    border>新车</el-radio>
          <el-radio v-model="product.carType"
                    label="准新车"
                    border>准新车</el-radio>
        </el-form-item>
        <el-form-item label="利润"
                      required>
          <el-col :span="7">
            <el-form-item>
              <el-input v-model.number="product.profit"
                        size="medium">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="产品信用等级"
                      required>
          <el-radio v-model="product.grade"
                    label="A"
                    border>A级(信用极好)</el-radio>
          <el-radio v-model="product.grade"
                    label="B"
                    border>B级(信用优秀)</el-radio>
          <el-radio v-model="product.grade"
                    label="C"
                    border>C级(信用良好)</el-radio>
          <el-radio v-model="product.grade"
                    label="D"
                    border>D级(信用中等)</el-radio>
          <el-radio v-model="product.grade"
                    label="E"
                    border>E级(信用不好)</el-radio>
        </el-form-item>
        <el-form-item label="资质要求"
                      required>
          <el-checkbox-group v-model="product.qualify">
            <el-checkbox label="大数据">大数据</el-checkbox>
            <el-checkbox label="征信">征信</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="方案"
                      required>
          <template v-for="(item, key) in planLoop">
            <el-col :key="key">
              <el-col :span="6">
                <el-form-item label-width="80px"
                              label="首付金额">
                  <el-input v-model.number="item.downpayAmount"
                            size="medium">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label-width="50px"
                              label="月供">
                  <el-input v-model.number="item.monthlyPay"
                            size="medium">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label-width="50px"
                              label="期数">
                  <el-input v-model.number="item.period"
                            size="medium">
                    <template slot="append">期</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="1">
                <el-button icon="el-icon-plus"
                           type="primary"
                           circle
                           size="mini"
                           v-if="key < 1"
                           @click="() => { planLoop.push({}) }"></el-button>
              </el-col>
              <el-col :span="1">
                <el-button icon="el-icon-minus"
                           type="danger"
                           circle
                           size="mini"
                           v-if="key < 1"
                           @click="() => { planLoop.length>1?planLoop.pop():null }"></el-button>
              </el-col>
            </el-col>
          </template>
        </el-form-item>
        <el-form-item label="可上牌城市"
                      required>
          <el-col :span="7">
            <el-form-item>
              <el-input type="textarea"
                        maxlength="45"
                        v-model="product.inUseCity"
                        placeholder="请输入上牌城市"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
      </div>
      <div class="breach-area">
        <div class="title">
          <div class="point"></div>
          <span>进件材料</span>
        </div>
        <el-form-item label="终审资料">
          <el-col :span="22">
            <el-collapse accordion>
              <el-collapse-item>
                <template slot="title">
                  <div class="collapse-item-title"><span>主贷人材料</span></div>
                </template>
                <el-checkbox-group v-model="product.lastAttrsList">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(lenderItem, key) in productMaterial.mainLender"
                          :key="key">
                    <el-button v-if="lenderItem.dataAttrId==='add'"
                               icon="el-icon-plus"
                               type="primary"
                               circle
                               size="mini"
                               @click="addLender('mainLender', 1)"></el-button>
                    <el-tooltip v-else
                                effect="dark"
                                :content="lenderItem.name"
                                placement="top">
                      <el-checkbox :label="JSON.stringify({dataAttrId:lenderItem.dataAttrId,targetType:lenderItem.targetType})">{{ lenderItem.name }}</el-checkbox>
                    </el-tooltip>
                  </el-col>
                </el-checkbox-group>
                <template v-if="productMaterial.mainLender.length%6 !== 0">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(item, key) in 6 - productMaterial.mainLender.length%6"
                          :key="key">
                  </el-col>
                </template>
              </el-collapse-item>
              <el-collapse-item>
                <template slot="title">
                  <div class="collapse-item-title"><span>配偶材料</span></div>
                </template>
                <el-checkbox-group v-model="product.lastAttrsList">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(lenderItem, key) in productMaterial.mateLender"
                          :key="key">
                    <el-button v-if="lenderItem.dataAttrId==='add'"
                               icon="el-icon-plus"
                               type="primary"
                               circle
                               size="mini"
                               @click="addLender('mateLender', 2)"></el-button>
                    <el-tooltip v-else
                                effect="dark"
                                :content="lenderItem.name"
                                placement="top">
                      <el-checkbox :label="JSON.stringify({dataAttrId:lenderItem.dataAttrId,targetType:lenderItem.targetType})">{{ lenderItem.name }}</el-checkbox>
                    </el-tooltip>
                  </el-col>
                </el-checkbox-group>
                <template v-if="productMaterial.mateLender.length%6 !== 0">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(item, key) in 6 - productMaterial.mateLender.length%6"
                          :key="key">
                  </el-col>
                </template>
              </el-collapse-item>
              <el-collapse-item>
                <template slot="title">
                  <div class="collapse-item-title"><span>担保人材料</span></div>
                </template>
                <el-checkbox-group v-model="product.lastAttrsList">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(lenderItem, key) in productMaterial.guarantorLender"
                          :key="key">
                    <el-button v-if="lenderItem.dataAttrId==='add'"
                               icon="el-icon-plus"
                               type="primary"
                               circle
                               size="mini"
                               @click="addLender('guarantorLender', 3)"></el-button>
                    <el-tooltip v-else
                                effect="dark"
                                :content="lenderItem.name"
                                placement="top">
                      <el-checkbox :label="JSON.stringify({dataAttrId:lenderItem.dataAttrId,targetType:lenderItem.targetType})">{{ lenderItem.name }}</el-checkbox>
                    </el-tooltip>
                  </el-col>
                </el-checkbox-group>
                <template v-if="productMaterial.guarantorLender.length%6 !== 0">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(item, key) in 6 - productMaterial.guarantorLender.length%6"
                          :key="key">
                  </el-col>
                </template>
              </el-collapse-item>
              <el-collapse-item>
                <template slot="title">
                  <div class="collapse-item-title"><span>担保人配偶材料</span></div>
                </template>
                <el-checkbox-group v-model="product.lastAttrsList">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(lenderItem, key) in productMaterial.guarantorMateLender"
                          :key="key">
                    <el-button v-if="lenderItem.dataAttrId==='add'"
                               icon="el-icon-plus"
                               type="primary"
                               circle
                               size="mini"
                               @click="addLender('guarantorMateLender', 4)"></el-button>
                    <el-tooltip v-else
                                effect="dark"
                                :content="lenderItem.name"
                                placement="top">
                      <el-checkbox :label="JSON.stringify({dataAttrId:lenderItem.dataAttrId,targetType:lenderItem.targetType})">{{ lenderItem.name }}</el-checkbox>
                    </el-tooltip>
                  </el-col>
                </el-checkbox-group>
                <template v-if="productMaterial.guarantorMateLender.length%6 !== 0">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(item, key) in 6 - productMaterial.guarantorMateLender.length%6"
                          :key="key">
                  </el-col>
                </template>
              </el-collapse-item>
              <el-collapse-item>
                <template slot="title">
                  <div class="collapse-item-title"><span>车辆材料</span></div>
                </template>
                <el-checkbox-group v-model="product.lastAttrsList">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(lenderItem, key) in productMaterial.carLender"
                          :key="key">
                    <el-button v-if="lenderItem.dataAttrId==='add'"
                               icon="el-icon-plus"
                               type="primary"
                               circle
                               size="mini"
                               @click="addLender('carLender', 9)"></el-button>
                    <el-tooltip v-else
                                effect="dark"
                                :content="lenderItem.name"
                                placement="top">
                      <el-checkbox :label="JSON.stringify({dataAttrId:lenderItem.dataAttrId,targetType:lenderItem.targetType})">{{ lenderItem.name }}</el-checkbox>
                    </el-tooltip>
                  </el-col>
                </el-checkbox-group>
                <template v-if="productMaterial.carLender.length%6 !== 0">
                  <el-col class="checkbox-item"
                          :span="4"
                          v-for="(item, key) in 6 - productMaterial.carLender.length%6"
                          :key="key">
                  </el-col>
                </template>
              </el-collapse-item>
            </el-collapse>
          </el-col>
        </el-form-item>
        <file-pic-up v-for="item in fileUploadList"
                     :key="item.dataAttrId"
                     :label-name="item.explain"
                     :file-name="'--' + item.explain || ''"
                     :product-name="product.productName"
                     :file-list="item.fileList"
                     :file-path.sync="item.filePath"
                     :example-loop.sync="item.exampleLoop"
                     @show="showImg"></file-pic-up>
        <video-view-up v-for="item in videoUploadList"
                       :key="item.dataAttrId"
                       :label-name="item.explain"
                       :upload-data="{videoName: 'video/' + item.explain}"
                       :video-list.sync="item.videoList"
                       :can-upload="true"></video-view-up>
        <el-form-item v-if="product.lastAttrsList.some(a => JSON.parse(a).dataAttrId===19 || JSON.parse(a).dataAttrId===57)"
                      label="保险单特别约定">
          <el-col :span="7">
            <el-input v-model="product.beneficiary"
                      size="medium"></el-input>
          </el-col>
        </el-form-item>
      </div>
      <div class="foot">
        <el-form-item>
          <el-button type="primary"
                     @click="publishProduct">发布</el-button>
          <el-button @click="() => {this.$router.go(-1)}">取消</el-button>
        </el-form-item>
      </div>
    </el-form>
    <el-dialog title="新增车型"
               :visible.sync="carDialog">
      <div>
        <el-form size="medium"
                 label-position="right"
                 label-width="200px">
          <el-form-item label="品牌">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="brandName"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车系">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="seriesName"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车型">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="modelName"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车辆指导价">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model.number="price"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车型年限">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="modelYear"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item label="车辆颜色">
            <el-col :span="7">
              <el-form-item>
                <el-input v-model="carColor"
                          size="medium"></el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
        </el-form>
      </div>
      <div class="foot">
        <el-button @click="addCar"
                   type="primary">新增</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新增材料"
               :visible.sync="lenderDialog">
      <el-checkbox-group v-model="newLenderPool.lenderCheckedList"
                         @change="lenderChecked=false">
        <el-tabs tab-position="left"
                 type="border-card"
                 style="height: 500px;overflow-y: scroll;">
          <el-tab-pane label="文本">
            <el-col :span="11"
                    v-for="(item, key) in newLenderPool.textLenders"
                    :key="key"
                    class="add-lender-item">
              <el-col :span="1">
                <el-checkbox :label="item.key"
                             :checked="lenderChecked"
                             @change="lenderChecked=!lenderChecked"
                             class="add-lender-checkbox"></el-checkbox>
              </el-col>
              <el-col :span="10">
                <el-input v-model="item.attrName"
                          :disabled="item.cantEdit"
                          size="mini">
                </el-input>
              </el-col>
            </el-col>
            <el-col :span="11"
                    class="add-lender-item">
              <el-button @click="pushLenderPool('textLenders', 4)"
                         size="mini"
                         type="primary">新增</el-button>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="图片">
            <el-col :span="11"
                    v-for="(item, key) in newLenderPool.picLenders"
                    :key="key"
                    class="add-lender-item">
              <el-row>
                <el-col :span="1"
                        class="fix-down">
                  <el-checkbox :label="item.key"
                               :checked="lenderChecked"
                               @change="lenderChecked=!lenderChecked"
                               class="add-lender-checkbox"></el-checkbox>
                </el-col>
                <el-col :span="10"
                        class="fix-down">
                  <el-input v-model="item.attrName"
                            :disabled="item.cantEdit"
                            size="mini">
                  </el-input>
                </el-col>
              </el-row>
              <el-row class="fix-upload">
                <el-col :span="6"
                        v-for="(exItem, exIndex) in item.exampleLoop"
                        :key="exIndex">
                  <pic-view :pic-url-list.sync="exItem.urls"
                            upload-class="short-upload"
                            :pic-name-list.sync="exItem.names"
                            :upload-data="{ picName: item.key }"
                            :group-index="exIndex"
                            :out-group-index="key"
                            :upload-type="item.cantEdit"
                            :max-size="1"
                            @showImg="showImg"
                            @lenderTrans="trans"></pic-view>
                  <div class="stalker">
                    <el-input placeholder="输入注释"
                              :disabled="item.cantEdit"
                              size="mini"
                              v-model="exItem.display"></el-input>
                  </div>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="11"
                    class="add-lender-item">
              <el-button @click="pushLenderPool('picLenders', 3)"
                         size="mini"
                         type="primary"
                         class="fix-down">新增</el-button>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="视频">
            <el-col :span="11"
                    v-for="(item, key) in newLenderPool.videoLenders"
                    :key="key"
                    class="add-lender-item">
              <el-col :span="1">
                <el-checkbox :label="item.key"
                             :checked="lenderChecked"
                             @change="lenderChecked=!lenderChecked"
                             class="add-lender-checkbox"></el-checkbox>
              </el-col>
              <el-col :span="10">
                <el-input v-model="item.attrName"
                          :disabled="item.cantEdit"
                          size="mini">
                </el-input>
              </el-col>
            </el-col>
            <el-col :span="11"
                    class="add-lender-item">
              <el-button @click="pushLenderPool('videoLenders', 7)"
                         size="mini"
                         type="primary">新增</el-button>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="文件">
            <el-col :span="11"
                    v-for="(item, key) in newLenderPool.fileLenders"
                    :key="key"
                    class="add-lender-item">
              <el-col :span="1">
                <el-checkbox :label="item.key"
                             :checked="lenderChecked"
                             @change="lenderChecked=!lenderChecked"
                             class="add-lender-checkbox">item.key</el-checkbox>
              </el-col>
              <el-col :span="10">
                <el-input v-model="item.attrName"
                          :disabled="item.cantEdit"
                          size="mini">
                </el-input>
              </el-col>
            </el-col>
            <el-col :span="11"
                    class="add-lender-item">
              <el-button @click="pushLenderPool('fileLenders', 6)"
                         size="mini"
                         type="primary">新增</el-button>
            </el-col>
          </el-tab-pane>
        </el-tabs>
      </el-checkbox-group>
      <div class="foot">
        <el-button @click="buildLender"
                   type="primary">确认</el-button>
        <el-button @click="lenderDialog = false"
                   plain>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.foot {
  padding-left: 30%;
}
.add-lender-item {
  padding: 5px 10px;
  background-color: #eee;
  margin: 5px 5px;
  & > div .fix-down {
    margin-top: 22px;
  }
  & > .fix-upload {
    margin-top: 5px;
  }
}
.add-lender-checkbox {
  margin: 4px 0 0 0 !important;
  & > .el-checkbox__label {
    display: none !important;
  }
}
.stalker {
  width: 79px;
}
.short-upload div {
  height: 79px;
}
</style>

<script>
import '@/style/common.scss'
import '@/style/info.scss'
import picView from '@/components/pic-viewer-up'
import vViewer from '@/components/v-viewer'
import filePicUp from '@/components/file-pic-up'
import videoViewUp from '@/components/video-viewer-up'
import { packageImgList } from '@/utils/imgPackage'
import { vListLength, validatenull, validateNumber } from '@/utils/validate'
import { api } from '@/api'
import { HTTPSUCCESS, HTTPDATAFAIL, HTTPPARAMFAIL, HTTPUNKOWNFAIL } from '@/components/constant'
import { devBaseURL } from '@/utils/http'
import { joinArray } from '@/utils/tool'
import { getToken } from '@/utils/auth'
import { material } from '@/utils/data'

export default {
  data() {
    return {
      lenderChecked: false,
      lenderDialog: false,
      productMaterial: material,
      isInfo: this.infoFlag === '1',
      cityList: [],
      companyList: [],
      planLoop: [{}],
      carDialog: false,
      brandName: null,
      seriesName: null,
      modelName: null,
      price: null,
      modelYear: null,
      carColor: null,
      uploadAction: devBaseURL + 'sys/supplier/upload',
      product: {
        lastAttrsList: [],
        brandList: [],
        seriesList: [],
        modelList: [],
        color: [],
        colorList: [],
        area: '1',
        cityIds: [],
        qualify: []
      },
      newLenderPool: {
        lastIndex: 0,
        lenderCheckedList: [],
        textLenders: [],
        picLenders: [],
        videoLenders: [],
        fileLenders: []
      },
      fileAllList: [],
      videoAllList: [],
      fileUploadList: [],
      videoUploadList: []
    }
  },
  activated() {
    this.reload()
    this.initialized()
    this.getProductDetail()
    this.getCityList()
    this.getCompanyList()
    this.geBrandList()
  },
  watch: {
    fileNeedList: {
      handler: function() {
        const allList = JSON.parse(JSON.stringify(this.fileNeedList))
        const uploadList = allList.map(e => {
          if (this.fileUploadList.some(a => a.dataAttrId === e.dataAttrId)) {
            const ele = this.fileUploadList.filter(a => a.dataAttrId === e.dataAttrId)
            return ele[0]
          } else {
            return e
          }
        })
        this.fileUploadList = JSON.parse(JSON.stringify(uploadList))
      }
    },
    videoNeedList: {
      handler: function() {
        const allList = JSON.parse(JSON.stringify(this.videoNeedList))
        const uploadList = allList.map(e => {
          if (this.videoUploadList.some(a => a.dataAttrId === e.dataAttrId)) {
            const ele = this.videoUploadList.filter(a => a.dataAttrId === e.dataAttrId)
            return ele[0]
          } else {
            return e
          }
        })
        this.videoUploadList = JSON.parse(JSON.stringify(uploadList))
      }
    }
  },
  computed: {
    fileNeedList() {
      return this.fileAllList.map(e => { if ([this.product.lastAttrsList].flatMap(f => f).some(g => JSON.parse(g).dataAttrId === e.dataAttrId)) { return e } }).filter(h => h != null)
    },
    videoNeedList() {
      return this.videoAllList.map(e => { if ([this.product.lastAttrsList].flatMap(f => f).some(g => JSON.parse(g).dataAttrId === e.dataAttrId)) { return e } }).filter(h => h != null)
    }
  },
  components: { picView, vViewer, filePicUp, videoViewUp },
  methods: {
    getToken,
    vListLength,
    joinArray,
    reload() {
      this.planLoop = [{}]
      this.product = {
        lastAttrsList: [],
        brandList: [],
        seriesList: [],
        modelList: [],
        color: [],
        colorList: [],
        area: '1',
        cityIds: [],
        productPicNameList: [],
        productPicUrlList: [],
        qualify: []
      }
      this.productMaterial = material
    },
    initialized() {
      this.$http.get(api.SYS_PRODUCT_INITIALIZE_MATERIAL, { productId: this.$route.params.productId }).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            const add = res.data
            if (!validatenull(this.$route.params.productId)) {
              const modifier = JSON.parse(JSON.stringify(material))
              modifier.mainLender.splice(modifier.mainLender.length - 1, 0, ...add.addMainLender)
              modifier.mateLender.splice(modifier.mateLender.length - 1, 0, ...add.addMateLender)
              modifier.guarantorLender.splice(modifier.guarantorLender.length - 1, 0, ...add.addGuarantorLender)
              modifier.guarantorMateLender.splice(modifier.guarantorMateLender.length - 1, 0, ...add.addGuarantorMateLender)
              modifier.carLender.splice(modifier.carLender.length - 1, 0, ...add.addCarLender)
              modifier.afterLoanLender.splice(modifier.afterLoanLender.length - 1, 0, ...add.addAfterLoanLender)
              modifier.mortgageLender.splice(modifier.mortgageLender.length - 1, 0, ...add.addMortgageLender)
              this.productMaterial = modifier
            }
            this.fileAllList = add.fileAllList
            this.videoAllList = add.videoAllList
          } else {
            this.$msg._message('查询失败 请联系系统管理员', 'error')
          }
        }
      )
    },
    getProductDetail() {
      if (!validatenull(this.$route.params.productId)) {
        this.$http._get(api.SYS_PRODUCT_DETAIL, this.$route.params.productId).then(
          res => {
            if (res.code === HTTPSUCCESS) {
              const detail = res.data
              this.fileAllList = detail.fileAllList || []
              this.videoAllList = detail.videoAllList || []
              const periodList = detail.period.split(',')
              const downpayAmountList = detail.downpayAmount.split(',')
              const monthlyPayList = detail.monthlyPay.split(',')
              const list = []
              periodList.forEach((e, i) => {
                list.push({ downpayAmount: downpayAmountList[i], monthlyPay: monthlyPayList[i], period: e })
              })
              this.planLoop = list
              detail.modelId = detail.carModelId
              if (!validatenull(detail.cityIds) && detail.cityIds.some(id => { return id === 1 })) {
                detail.area = '1'
                detail.cityIds = []
              } else {
                detail.area = '2'
              }
              detail.qualify = detail.qualify || []
              detail.lastAttrsList = detail.lastAttrsList || []
              detail.color = [detail.color] || null
              this.product = detail
              const productPicList = packageImgList([detail.productPic])
              this.product.productPicNameList = productPicList[0]
              this.product.productPicUrlList = productPicList[1]
            } else {
              this.$msg._message('查询失败 请联系系统管理员', 'error')
            }
          }
        )
      }
    },
    addCar() {
      if (validatenull(this.brandName)) return this.$msg._message('请输入品牌', 'warning')
      if (validatenull(this.seriesName)) return this.$msg._message('请输入车系', 'warning')
      if (validatenull(this.modelName)) return this.$msg._message('请输入车型', 'warning')
      if (validatenull(this.price)) return this.$msg._message('请输入车辆指导价', 'warning')
      if (validatenull(this.carColor)) return this.$msg._message('请输入车辆颜色', 'warning')
      if (!validateNumber(this.price)) return this.$msg._message('车辆指导价必须为数字', 'warning')
      const params = {
        brandName: this.brandName,
        seriesName: this.seriesName,
        modelName: this.modelName,
        price: this.price,
        color: this.carColor,
        modelYear: this.modelYear
      }
      this.$http.post(api.SYS_CAR_ADD, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('车型新增成功！', 'success')
            this.carDialog = false
            this.product.brandList = [res.data.carBrand]
            this.product.seriesList = [res.data.carSeries]
            this.product.modelList = [res.data.carModel]
            this.product.brandId = res.data.carBrand.brandId
            this.product.seriesId = res.data.carSeries.seriesId
            this.product.modelId = res.data.carModel.modelId
            this.product.carModelId = res.data.carModel.modelId
            this.product.color = [this.carColor]
            this.product.colorList = [this.carColor]
          } else {
            this.$msg._message('车型新增失败 请联系系统管理员', 'error')
          }
        }
      )
    },
    getCityList() {
      this.$http.get(api.SYS_CITY_CITYS).then(
        res => {
          this.cityList = res.data
        }
      )
    },
    getCompanyList() {
      this.$http.get(api.SYS_SUPPLIER_ALL).then(
        res => {
          this.companyList = res.data
        }
      )
    },
    geBrandList() {
      this.$http.get(api.SYS_CITY_CARBRANDS).then(
        res => {
          this.product.brandList = res.data
        }
      )
    },
    getCarSeries(brandId) {
      this.$http._get(api.SYS_CITY_CARSERIES, brandId).then(
        res => {
          this.product.seriesList = res.data
        }
      )
    },
    getCarModel(seriesId) {
      this.$http._get(api.SYS_CITY_CARMODELS, seriesId).then(
        res => {
          this.product.modelList = res.data
        }
      )
    },
    setCarModelAndColors() {
      const carModel = this.product.modelList.filter(item =>
        item.modelId === this.product.modelId
      )
      this.product.colorList = carModel[0].colorsJson
      this.product.carModelId = carModel[0].modelId
      this.product.carPrice = carModel[0].price
    },
    publishProduct() {
      if (validatenull(this.product.productPicNameList)) return this.$msg._message('请上传产品图片', 'warning')
      if (validatenull(this.product.area)) return this.$msg._message('请选择区域', 'warning')
      if (this.product.area === '2' && validatenull(this.product.cityIds)) return this.$msg._message('请选择区域', 'warning')
      if (validatenull(this.product.supplierId)) return this.$msg._message('请选择金融公司', 'warning')
      if (validatenull(this.product.productName)) return this.$msg._message('请填写方案名称', 'warning')
      if (validatenull(this.product.carModelId)) return this.$msg._message('请选择车型', 'warning')
      if (validatenull(this.product.color)) return this.$msg._message('请选择颜色', 'warning')
      if (validatenull(this.product.qualify)) return this.$msg._message('请选择资质要求', 'warning')
      if (validatenull(this.product.carType)) return this.$msg._message('请选择车辆类型', 'warning')
      if (validatenull(this.product.grade)) return this.$msg._message('请选择产品信用等级', 'warning')
      if (validatenull(this.product.profit)) return this.$msg._message('请填写总利润', 'warning')
      if (!validateNumber(this.product.profit)) return this.$msg._message('总利润必须为数字', 'warning')
      if (validatenull(this.product.inUseCity)) return this.$msg._message('请填写可上牌城市', 'warning')
      if (validatenull(this.product.lastAttrsList)) return this.$msg._message('请至少勾选主贷人需要材料', 'warning')
      if (this.product.lastAttrsList.some(a => JSON.parse(a).dataAttrId === 19) && validatenull(this.product.beneficiary)) return this.$msg._message('终审材料已经勾选保险单，请填写保险单特别约定', 'warning')
      if (this.planLoop.some(a => { validatenull(a.downpayAmount) || validatenull(a.monthlyPay) || validatenull(a.period) })) return this.$msg._message('请填写完整方案', 'warning')
      if (this.planLoop.some(a => { validateNumber(a.downpayAmount) || validateNumber(a.monthlyPay) || validateNumber(a.period) })) return this.$msg._message('方案内只允许填写数字', 'warning')
      if (validatenull(this.fileUploadList)) {
        if (this.fileUploadList.some(e => validatenull(e.filePath))) return this.$msg._message('请上传文件', 'warning')
        this.fileUploadList.forEach(e => {
          if (e.exampleLoop && e.exampleLoop.some(a => (vListLength(a.names) && !validatenull(a.display)) || (!vListLength(a.names) && validatenull(a.display)))) return this.$msg._message('文件示例和描述需要填写完整！', 'warning')
        })
      }
      if (validatenull(this.videoUploadList)) {
        if (this.videoUploadList.some(e => validatenull(e.videoList))) return this.$msg._message('请上传示例视频', 'warning')
      }
      if (this.product.area === '1') this.product.cityIds = [1]
      const fileList = JSON.parse(JSON.stringify(this.fileUploadList))
      fileList.map(
        e => {
          e.example = joinArray(e.exampleLoop.flatMap(a => a.names))
          e.displays = joinArray(e.exampleLoop.map(a => a.display))
          delete e['fileList']
          delete e['exampleLoop']
        }
      )
      const videoList = JSON.parse(JSON.stringify(this.videoUploadList))
      videoList.map(
        e => {
          e.videoName = joinArray(e.videoList.map(a => a.name))
          delete e['videoList']
        }
      )
      const params = {
        productId: this.$route.params.productId || null,
        businessType: 3,
        businessName: '以租代购现车',
        status: 0,
        cityIds: this.product.cityIds,
        productPic: this.product.productPicNameList.join(','),
        supplierId: this.product.supplierId,
        supplierName: this.product.supplierName,
        productName: this.product.productName,
        carModelId: this.product.carModelId,
        carColor: this.product.color.join(','),
        downpayAmount: this.planLoop.map(a => a.downpayAmount).join(','),
        monthlyPay: this.planLoop.map(a => a.monthlyPay).join(','),
        period: this.planLoop.map(a => a.period).join(','),
        profit: this.product.profit,
        inUseCity: this.product.inUseCity,
        carType: this.product.carType,
        grade: this.product.grade,
        qualify: joinArray(this.product.qualify),
        lastAttrsList: this.product.lastAttrsList.map(e => JSON.parse(e)),
        fileList: fileList.length > 0 ? fileList : null,
        videoList: videoList.length > 0 ? videoList : null,
        beneficiary: this.product.beneficiary
      }
      this.$http.post(api.SYS_PRODUCT_NEW, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('产品上架成功！', 'success')
            this.$router.go(-1)
          } else {
            this.$msg._message('产品上架失败 请联系系统管理员', 'error')
          }
        }
      )
    },
    setDetail(supplierId) {
      const supplier = this.companyList.filter(item =>
        item.value === supplierId
      )
      this.product.supplierName = supplier[0].label
      this.product.manager = supplier[0].productManager
      this.product.managerPhone = supplier[0].phone
    },
    addLender(parentKey, targetType) {
      this.product._targetType = targetType
      this.product._parentKey = parentKey
      this.$http.get(api.SYS_PRODUCT_NEW_LENDER_POOL).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.newLenderPool = res.data
            if (this.newLenderPool.picLenders && this.newLenderPool.picLenders.length > 0) {
              this.newLenderPool.picLenders.map(e => {
                if (!e.cantEdit) {
                  e.exampleLoop.push([{}])
                }
              })
            }
            this.newLenderPool.lenderCheckedList = []
            this.lenderDialog = true
          } else {
            this.$msg._message('请联系系统管理员', 'error')
          }
        }
      )
    },
    buildLender() {
      if (this.newLenderPool.picLenders.some(e => e.exampleLoop && e.exampleLoop.some(a => (vListLength(a.names) && !validatenull(a.display)) || (!vListLength(a.names) && validatenull(a.display))))) return this.$msg._message('新增材料的图片示例和描述需要填写完整！', 'warning')
      let newLenders = [
        ...this.newLenderPool.textLenders,
        ...this.newLenderPool.picLenders,
        ...this.newLenderPool.videoLenders,
        ...this.newLenderPool.fileLenders]
      newLenders.map(
        e => {
          if (e.exampleLoop) {
            e.examplePicNameList = e.exampleLoop.map(a => { if (a.names) return a.names[0] }).filter(b => b)
            e.tips = joinArray(e.exampleLoop.map(a => { if (a.display) return a.display }).filter(b => b))
            delete e['exampleLoop']
          }
          if (e && e.attrName != null) return e
        })
      this.newLenderPool.lenderCheckedList.forEach(
        lender => {
          newLenders = newLenders.map(
            e => {
              if (e.key === lender) { e.selected = true }
              return e
            }
          )
        }
      )
      const params = {
        newLenderPool: newLenders
      }
      this.$http.post(api.SYS_PRODUCT_NEW_LENDER, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('新增材料成功！', 'success')
            this.fileAllList = res.data.fileAllList
            this.videoAllList = res.data.videoAllList
            const lastPool = res.data.lastPool
            lastPool.forEach(
              ele => {
                if (ele.selected) {
                  this.productMaterial[this.product._parentKey].splice(this.productMaterial[this.product._parentKey].length - 1, 0, { dataAttrId: ele.dataAttrId, name: ele.attrName, targetType: this.product._targetType })
                }
              }
            )
            this.lenderDialog = false
          } else {
            this.$msg._message('请联系系统管理员', 'error')
          }
        }
      )
    },
    pushLenderPool(poolKey, type) {
      const newKey = ++this.newLenderPool.lastIndex
      if (poolKey === 'picLenders') {
        this.newLenderPool[poolKey].push({ key: 'value' + newKey, type: type, exampleLoop: [{}] })
      } else {
        this.newLenderPool[poolKey].push({ key: 'value' + newKey, type: type })
      }
    },
    showImg(url) {
      this.$refs.view.showImg(url)
    },
    trans(index, outIndex, flag) {
      if (flag === 'success') {
        this.newLenderPool.picLenders[outIndex].exampleLoop.push({})
      } else if (flag === 'remove') {
        this.newLenderPool.picLenders[outIndex].exampleLoop.splice(index, 1)
      }
    }
  }
}
</script>
